package com.eight.travel.interceptor;

import com.alibaba.fastjson.JSON;
import com.eight.travel.utils.BaseResp;
import com.eight.travel.utils.JWTUtils;
import io.swagger.annotations.Api;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;




/**
 * @author Q小旭
 * @version 1.0
 */
@Api(value = "拦截验证")
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前置拦截
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies==null || cookies.length==0){
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            BaseResp fail =new BaseResp().FAIL("未登录!");
            writer.write(JSON.toJSONString(fail));
            return false;
        }
        for (Cookie co:cookies){
            if (co.getName().equals("token")){
                token=co.getValue();
            }
        }
        if (StringUtils.isEmpty(token)){
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            BaseResp fail =new BaseResp().FAIL("未登录!");
            writer.write(JSON.toJSONString(fail));
            return false;
        }
        //使用jwt解析token
        Map map = JWTUtils.verfiyJWT(token);
        if (map==null){
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            BaseResp fail =new  BaseResp().FAIL("登录信息有误!");
            writer.write(JSON.toJSONString(fail));
            return false;
        }
        return true;

    }
}

